import type { IPath } from '@/interfaces';
import type { QueryKey } from '@tanstack/query-core';
import type { TError, TMetadata } from '@/types';
import { queryPath } from '@/services/api';
import { useQuery } from '@tanstack/react-query';

const rootPath = '/paths';

export default function useUser(
  queryKey?: QueryKey | TMetadata | IPath,
  initialData?: IPath,
) {
  let _queryKey = [rootPath, '/'];
  let _initialData = initialData;

  if (queryKey) {
    if (Array.isArray(queryKey)) {
      _queryKey = queryKey[0] === rootPath ? queryKey : [rootPath, ...queryKey];
    } else if ('all' in queryKey && queryKey.all['page']) {
      _queryKey = queryKey.all['page'].k as any;
      _initialData = queryKey.all['page'].v as IPath;
    } else {
      _initialData = queryKey as IPath;
    }
  }

  return useQuery<IPath, TError>(
    _queryKey,
    async (context) => {
      return (await queryPath({
        query: {
          name: context.queryKey[1],
        },
      })) as IPath;
    },
    {
      initialData: _initialData,
    },
  );
}
